import { UserOutlined } from "@ant-design/icons";
import { Button, Form, Input, Modal } from "antd";
import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { LOGIN_PATHNAME } from "../../router";
import useGetUserInfo from "../../hooks/useGetUserInfo";
import { useDispatch } from "react-redux";
import { loginReducer, logoutReducer } from "../../store/userInfoReducer";
import { useRequest } from "ahooks";
import {
  changePasswordService,
  changeNickNameService,
} from "../../services/user";
import { MD5 } from "crypto-js";
import { clearPersistor } from "../../utils/common";

const ChangeNickNameElement: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const { userName, isAdmin, userId } = useGetUserInfo();
  const { run } = useRequest(
    async (values) => {
      const { nickName } = values;
      return await changeNickNameService(nickName);
    },
    {
      manual: true,
      onSuccess() {
        dispatch(
          loginReducer({
            userName,
            isAdmin,
            nickName: form.getFieldValue("nickName"),
            userId,
          })
        );
        form.resetFields();
        setIsModalOpen(false);
      },
    }
  );

  function changeNickName() {
    form
      .validateFields()
      .then((values) => run(values))
      .catch(() => null);
  }

  return (
    <>
      <Button type="link" onClick={() => setIsModalOpen(true)}>
        修改昵称
      </Button>
      <Modal
        title="修改昵称"
        closeIcon={false}
        keyboard={false}
        maskClosable={false}
        open={isModalOpen}
        onOk={changeNickName}
        onCancel={() => setIsModalOpen(false)}
      >
        <Form labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} form={form}>
          <Form.Item
            label="昵称"
            name="nickName"
            rules={[
              {
                required: true,
                message: "请输入新昵称",
              },
              {
                type: "string",
                min: 2,
                max: 20,
                message: "字符长度在2-20之间",
              },
            ]}
          >
            <Input allowClear />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

const ChangePasswordElement: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const { run } = useRequest(
    async (values) => {
      const { oldPassword, password } = values;
      return await changePasswordService(
        MD5(oldPassword).toString(),
        MD5(password).toString()
      );
    },
    {
      manual: true,
      onSuccess() {
        form.resetFields();
        setIsModalOpen(false);
      },
    }
  );

  function changePassword() {
    form
      .validateFields()
      .then((values) => run(values))
      .catch(() => null);
  }

  return (
    <>
      <Button type="link" onClick={() => setIsModalOpen(true)}>
        修改密码
      </Button>
      <Modal
        title="修改密码"
        closeIcon={false}
        keyboard={false}
        maskClosable={false}
        open={isModalOpen}
        onOk={changePassword}
        onCancel={() => setIsModalOpen(false)}
      >
        <Form labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} form={form}>
          <Form.Item
            label="旧密码"
            name="oldPassword"
            rules={[
              {
                required: true,
                message: "请输入旧密码",
              },
              {
                type: "string",
                min: 6,
                max: 20,
                message: "字符长度在6-20之间",
              },
            ]}
          >
            <Input.Password allowClear />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="password"
            rules={[
              {
                required: true,
                message: "请输入新密码",
              },
              {
                type: "string",
                min: 6,
                max: 20,
                message: "字符长度在6-20之间",
              },
            ]}
          >
            <Input.Password allowClear />
          </Form.Item>
          <Form.Item
            label="确认密码"
            name="confirm"
            dependencies={["password"]}
            rules={[
              {
                required: true,
                message: "请再次输入新密码",
              },
              {
                type: "string",
                min: 6,
                max: 20,
                message: "字符长度在6-20之间",
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue("password") === value) {
                    return Promise.resolve();
                  } else {
                    return Promise.reject(new Error("两次密码不一致"));
                  }
                },
              }),
            ]}
          >
            <Input.Password allowClear />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

const UserInfo: React.FC = () => {
  const nav = useNavigate();
  const dispatch = useDispatch();
  const { userName, nickName, isAdmin } = useGetUserInfo();

  function logout() {
    dispatch(logoutReducer());
    clearPersistor();
    nav(LOGIN_PATHNAME);
  }

  if (!userName) return <Link to={LOGIN_PATHNAME}>登录</Link>;

  return (
    <>
      <span
        style={{
          marginRight: "10px",
          paddingTop: "1px",
          color: isAdmin ? "red" : "#e8e8e8",
        }}
      >
        <UserOutlined />
        {nickName}
      </span>
      <ChangeNickNameElement />
      <ChangePasswordElement />
      <Button type="link" onClick={logout}>
        退出
      </Button>
    </>
  );
};

export default UserInfo;
